/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-25，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.ui.fragment;

import java.util.List;
import java.util.Map;
import com.chinamobile.ln.ictenterprises.R;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.Constants;
import com.chinamobile.ln.ictenterprises.common.Controller;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.model.request.SearchHistory;
import com.chinamobile.ln.ictenterprises.model.response.ResponseHistory;
import com.chinamobile.ln.ictenterprises.model.response.ResponseHistory.Records;
import com.chinamobile.ln.ictenterprises.ui.activity.LoginActivity;
import com.chinamobile.ln.ictenterprises.ui.activity.MsgDetailActivity;
import com.chinamobile.ln.ictenterprises.ui.adapter.OverSendAdapter;
import com.chinamobile.ln.ictenterprises.utils.JsonUtil;
import com.chinamobile.ln.ictenterprises.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

@SuppressLint("HandlerLeak")
public class OverSendFragment extends Fragment implements OnItemClickListener
{
    private Context context;
    private OverSendAdapter adapter;
    private ListView listView;
    private List<Records> listRecords;
    private String currPage = "1";
    private String allPage = "1";
    private Controller mHttpManager = null;
    private SharedPreferences sharedPref;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        context = getActivity();
        mHttpManager = Controller.getInstance();
        sharedPref = context.getSharedPreferences(Constants.LOGIN_SHAREDPREF,
            Context.MODE_PRIVATE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_list_oversend, null);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
    }

    @Override
    public void onResume()
    {
        // TODO Auto-generated method stub
        currPage="1";
        getData(currPage);
        super.onResume();
     
    }

    /**
     * 初始化已发送列表
     */
    private void getData(String currPage)
    {
        SearchHistory searchHistory = new SearchHistory(
            GlobalSetting.GET_FOR_PAGE, Constants.REQUEST_TYPE_OVER_SEND,
            currPage);
        String params = JsonUtil.objectToJson(searchHistory);
        Log.i("OverSendFragment", "请求参数：" + params);
        Step step = Utils.paramsUtil(Config.SEND_MSG, params);
        HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
            HttpAsyncTask.CACHE_TYPE_ACTION, sharedPref.getString(
                Constants.COOKIES, ""), GlobalSetting.GET_HISTORY);
        httpAsyncTask.setUIHandler(getHistoryHandler);
        mHttpManager.execute(httpAsyncTask);
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg)
        {
            currPage = String.valueOf(Integer.parseInt(currPage) + 1);
            getData(currPage);
        }
    };

    private Handler getHistoryHandler = new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            if (msg.obj != null)
            {
                Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                int reultCode = (Integer) httpMap
                    .get(GlobalSetting.STUATUS_CODE);
                if (reultCode == GlobalSetting.STUATUS_CODE_SUCCESS)
                {
                    ResponseHistory responseHistory = (ResponseHistory) httpMap
                        .get(GlobalSetting.JSON_HISTORY);
                    if (responseHistory != null)
                    {
                        if (responseHistory.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_SUC))
                        {
                            List<Records> list = responseHistory.results.records;
                            currPage = responseHistory.results.page;
                            allPage = responseHistory.results.totalPageCount;
                            if (currPage.equals("1"))
                            {
                                listRecords = list;
                            }
                            else
                            {
                                listRecords.addAll(list);
                            }
                            setView();
                        }
                        else if (responseHistory.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_FAIL))
                        {
                            Toast
                                .makeText(context, R.string.get_over_send_fail,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    else
                    {
                        Toast.makeText(context, R.string.get_over_send_fail,
                            Toast.LENGTH_SHORT).show();
                    }
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_INVALIDATION)
                {
                    Toast.makeText(context, R.string.session_timeout,
                        Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_TIMEROUT)
                {
                    Toast.makeText(context, R.string.network_error,
                        Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(context, R.string.get_over_send_fail,
                    Toast.LENGTH_SHORT).show();
            }
        };
    };

    public void setView()
    {
        if (listRecords.size() > 0)
        {
            if (adapter == null)
            {
                adapter = new OverSendAdapter(context, listRecords, handler,
                    currPage, allPage);
                listView.setAdapter(adapter);
            }
            else
            {
                adapter.list = listRecords;
                adapter.currPage = currPage;
                adapter.allPage = allPage;
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
        long arg3)
    {
        Records records = (Records) parent.getAdapter().getItem(position);
        Intent intent = new Intent();
        intent.putExtra("id", records.id);
        intent.putExtra("isSendOver", true);
        intent.setClass(getActivity(), MsgDetailActivity.class);
        startActivity(intent);
    }
}
